package cn.zzszxyy.hr.support;

import cn.zzszxyy.hr.comm.Global;
import cn.zzszxyy.hr.model.MenuEntity;
import cn.zzszxyy.hr.model.UserEntity;
import cn.zzszxyy.hr.service.MenuService;
import cn.zzszxyy.hr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 作者:张伟
 * <p>
 * 联系:adamzzww@163.com
 * 时间:2016-11-26
 * 说明:无
 */
public class IdentityVerificationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、配置文件中设置过滤器例外，实现：（1）GET请求到登录页面orPOST请求到登录验证 放行
        // （2）退出、首页等页面无需登录，即此处要放行 允许游客的请求
//        String requestPath = request.getServletPath();
//        boolean flag = (requestPath.startsWith(Global.LOGIN_PAGE)) ||
//                (requestPath.startsWith(Global.LOGIN_POST));
//        if (flag)  {
//            return true;
//        }
        UserEntity curUser = (UserEntity) request.getSession().getAttribute(Global.COOKIE_USER_OBJECT);
        //2、如果用户已经登录 放行
        if (null != curUser) {
            if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
                AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
                //没有声明需要权限,或者声明不验证权限
                if (authPassport == null || authPassport.validate() == false) {
                    return true;
                } else {
                    //在这里实现自己的权限验证逻辑
                    boolean flag = false;
                    //1. 读取用户访问地址
                    String requestUri = request.getRequestURI();
                    String contextPath = request.getContextPath();
                    String url = requestUri.substring(contextPath.length());
                    //2. 匹配数据库中url是否存在
                    if (validateUserMenus(menuService.findMenusByUserId(curUser.getUserId()), url, request.getMethod()))//如果验证成功返回true（这里直接写false来模拟验证失败的处理）
                        return true;
                    else//如果验证失败
                    {
                        //重定向到登录页面
                        response.sendRedirect(request.getContextPath() + Global.LOGIN_PAGE);
                        return false;
                    }
                }
            } else {
                return true;
            }
        } else {
            // 跳转到：登录超时页面

        }
        //4、非法请求 即这些请求需要登录后才能访问
        //重定向到登录页面
        response.sendRedirect(request.getContextPath() + Global.LOGIN_PAGE);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        if (modelAndView == null) return;
//        //String id = request.getSession().getAttribute(Global.Web.COOKIE_USER_ID).toString();
//        try {
//            //UserEntity user = userService.findOne(Integer.parseInt(id));
//            UserEntity user = (UserEntity) request.getSession().getAttribute(Global.Web.COOKIE_USER_OBJECT);
//            modelAndView.addObject(Global.Web.JSP_USER_OBJECT, user);
//        } catch (Exception ex) {
//            //重定向到登录页面
//            response.sendRedirect(request.getContextPath() + Global.Web.LOGIN_PAGE);
//        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean validateUserMenus(List<MenuEntity> menuList, String visitUrl, String reqMethod) {
        boolean flag = false;
        for (MenuEntity menu : menuList) {
            if (!((null == menu.getReqMethod()) || (null == menu.getMenuUrl()))) {
                if (visitUrl.toUpperCase().contains(menu.getMenuUrl().toUpperCase())) { //(reqMethod.toUpperCase().equals(menu.getReqMethod().toUpperCase())
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

}
